import 'package:flutter/material.dart';

class LazyInitIndexedStack extends StatefulWidget {
  final int index;
  final List<WidgetBuilder> builders;

  const LazyInitIndexedStack({
    super.key,
    this.index = 0,
    required this.builders,
  });

  @override
  State<LazyInitIndexedStack> createState() => _LazyInitIndexedStackState();
}

class _LazyInitIndexedStackState extends State<LazyInitIndexedStack> {
  Map<int, Widget> widgetMap = {};
  int current = 0;
  Set<int> initIndex = {};

  @override
  void initState() {
    super.initState();
    handleIndexChange(widget.index);
  }

  @override
  Widget build(BuildContext context) {
    return IndexedStack(
      index: widget.index,
      children: <Widget>[
        for (var i = 0; i < widget.builders.length; i++) buildItem(i),
      ],
    );
  }

  @override
  void didUpdateWidget(LazyInitIndexedStack oldWidget) {
    super.didUpdateWidget(oldWidget);
    var newIndex = widget.index;
    if (oldWidget.index != newIndex) {
      current = newIndex;
      handleIndexChange(newIndex);
      setState(() {});
    }
  }

  void handleIndexChange(int newIndex) {
    if (!initIndex.contains(newIndex)) {
      final w = widget.builders[newIndex](context);
      initIndex.add(newIndex);
      widgetMap[newIndex] = w;
    }
  }

  Widget buildItem(int i) {
    if (initIndex.contains(i)) {
      return widgetMap[i] ?? Container();
    } else {
      return Container();
    }
  }
}
